/**
 * 登录表单组件
 */

import React, { useState } from 'react';
import { Form, Input, Button, Checkbox, message } from 'antd';
import { UserOutlined, LockOutlined } from '@ant-design/icons';
import { loginService } from '../../api';
import { LoginFormData, LoginFormProps } from './types';
import styles from './LoginForm.module.css';

const LoginForm: React.FC<LoginFormProps> = ({ onLoginSuccess, onLoginError }) => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);

  const handleSubmit = async (values: LoginFormData) => {
    try {
      setLoading(true);
      const response = await loginService.login({
        username: values.username,
        password: values.password,
        remember: values.remember,
      });
      
      loginService.setToken(response.token);
      message.success('登录成功');
      onLoginSuccess?.();
    } catch (error) {
      message.error('登录失败，请检查用户名和密码');
      onLoginError?.(error as Error);
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className={styles.container}>
      <h2 className={styles.title}>用户登录</h2>
      <Form
        form={form}
        name="login"
        onFinish={handleSubmit}
        autoComplete="off"
        className={styles.form}
      >
        <Form.Item
          name="username"
          rules={[{ required: true, message: '请输入用户名' }]}
        >
          <Input
            prefix={<UserOutlined />}
            placeholder="用户名"
            size="large"
          />
        </Form.Item>

        <Form.Item
          name="password"
          rules={[{ required: true, message: '请输入密码' }]}
        >
          <Input.Password
            prefix={<LockOutlined />}
            placeholder="密码"
            size="large"
          />
        </Form.Item>

        <Form.Item name="remember" valuePropName="checked">
          <Checkbox>记住我</Checkbox>
        </Form.Item>

        <Form.Item>
          <Button
            type="primary"
            htmlType="submit"
            loading={loading}
            size="large"
            block
          >
            登录
          </Button>
        </Form.Item>
      </Form>
    </div>
  );
};

export default LoginForm; 